<template>
  <div class="container">
    <template v-for="(item, index) in accountRecharges">
      <el-badge
        :key="index"
        :value="`第 ${index + 1} 张`"
        class="item mb2"
        type="primary"
      >
        <span>发票所属时间: {{ new Date().format("yyyy年MM月dd日") }}</span>

        <table
          :key="index"
          align="center"
          bgcolor="#ccc"
          border="0"
          cellpadding="10"
          cellspacing="1"
          class="tabtop13"
          width="100%"
        >
          <tr>
            <td
              class="font-center"
              colspan="1"
              width="20%"
            >{{ item.InvoiceType }}</td>
            <td
              class="font-center"
              colspan="4"
              width="20%"
            >{{ item.payingBankName }}</td>
            <td
              class="font-center titfont"
              colspan="4"
              width="100%"
            >发票版面 | 一百万元版</td>
          </tr>
          <tr>
            <td colspan="1">客户</td>
            <td colspan="4">{{ item.BuyerName }}</td>
            <td colspan="2">服务商</td>
            <td colspan="2">{{ item.SellerName }}</td>
          </tr>
          <tr>
            <td width="5%">货物或应税劳务、服务名称</td>
            <td width="5%">规格</td>
            <td width="5%">单位</td>
            <td width="5%">数量</td>
            <td width="5%">单价</td>
            <td width="5%">金额</td>
            <td width="5%">税率</td>
            <td width="5%">税额</td>
            <td width="20%">含税金额(最大值:1059998)</td>
          </tr>
          <tr>
            <td>{{ item.Invoicesubject }}</td>
            <td></td>
            <td></td>
            <td>1</td>
            <td></td>
            <td>{{ item.Amount }}</td>
            <td>6%</td>
            <td>{{ item.TaxAmount }}</td>
            <td>
              <el-form
                :model="item"
                :rules="AmountRule"
              >{{ item.InvoiceTaxAmount }}</el-form>
            </td>
          </tr>
          <tr>
            <td>价税合计</td>
            <td colspan="8">{{ $common.toFixed2(item.InvoiceTaxAmount) }}</td>
          </tr>
          <tr>
            <td>备注</td>
            <td colspan="8">
              <xy-input
                type="textarea"
                v-model="item.Remarks"
              ></xy-input>
            </td>
          </tr>
        </table>
        <!-- <div class="add-item font-center mt-1">
          <el-button
            @click="addTable(item, index)"
            icon="el-icon-scissors"
            round
            size="small"
            type="success"
          >拆分</el-button>
        </div>-->
      </el-badge>
    </template>

    <div class="invoice-operation row jcsb aic">
      <p>
        可开票总额:
        <b>￥{{ $common.toFixed2(InvoiceBlanceAmount) }}</b>
      </p>
      <p>
        申请开票总额:
        <b>￥{{ $common.toFixed2(invoiceTotalAmount) }}</b>
      </p>
      <!-- <p>
        差额::
        <b class="red">￥{{ $common.toFixed2(InvoiceBlanceAmount - invoiceTotalAmount) }}</b>
      </p>-->

      <div class="cancel">
        <el-button
          @click="$router.replace(`/invoiceApplyList`)"
          type="info"
        >取消</el-button>
      </div>
      <div class="submit">
        <el-button
          @click="onSubmit"
          type="primary"
        >
          {{
          $language.local("Submit")
          }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    const validateAmount = (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error("请输入正确的发票金额！"));
        return;
      }
      let item = this.accountRecharges.find((v) => v.Amount == value);

      let istems = this.accountRecharges.filter((v) => v.MID === item.MID);
      let total = istems.reduce((total, cur) => total + cur.Amount, 0);

      if (total > item.InvoiceBlanceAmount) {
        callback(new Error("超过可开发票金额！"));
      } else {
        callback();
      }
    };
    return {
      remark: "",
      invoices: [],
      accountRecharges: [],
      InvoiceBlanceAmount: 0,
      // 金额
      inputAmount: "",
      nowDate: new Date().toLocaleDateString(),
      serviceName: "",
      options: [],
      AmountRule: {
        Amount: [
          { required: true, message: "请输入金额", trigger: "blur" },
          { type: "number", message: "必须为数字值" },
          { validator: validateAmount, trigger: "blur" },
        ],
      },
      invoice: {
        Id: 0,
        MID: 0,
        TBID: 0,
        Invoicesubject: "发票主体",
        InvoicesubjectId: "发票账号",
        unioninvoice: "联合发票",
        MerchantCode: "纳税人识别号",
        MerchantName: "客户名称",
        // ApplicationTime: "2021-06-07T01:17:20.059Z",
        ServiceProviderId: 0,
        ServiceProviderName: "string",
        InvoiceRise: "发票抬头",
        Amount: 0,
        InvoiceTypeId: 0,
        InvoiceType: "string",
        InvoiceStatus: "string",
        InvoiceBusinessStatus: 0,
        Remarks: "string",
        InvoiceCategory: "发票类别",
        InvoiceCode: "发票代码",
        InvoiceNumber: "发票号码",
        TaxAmount: "税额",
        InvoiceTaxAmount: "发票税额",
        Indate: "2021-06-07T01:17:20.059Z",
        Rate: "税率",
        InvoiceFilePath: "string",
        wlgs: "string",
        wldh: "string",
      },
    };
  },
  computed: {
    invoiceTotalAmount() {
      console.log(this.accountRecharges);
      return this.accountRecharges.reduce(
        (total, cur) => total + cur.InvoiceTaxAmount,
        0
      );
    },
  },
  async mounted() {
    this.getInvoiceList();
  },

  methods: {
    async getInvoiceList() {
      let { ids } = this.$route.params;

      if (ids && ids.length > 0) {
        const response = await this.$http.get(
          "/api/invoiceApply/GetInvoiceListByIDS",
          { ids }
        );
        console.log(response);
        this.accountRecharges = [...response.data.Data];
        this.InvoiceBlanceAmount = this.accountRecharges.reduce(
          (total, cur) => total + cur.InvoiceTaxAmount,
          0
        );
        console.log(this.InvoiceBlanceAmount);
      } else {
        this.$router.replace("/invoiceApplyList");
      }
    },
    addTable(item, index) {
      console.log(index);
      const items = this.accountRecharges.filter((v) => v.MID === item.MID);
      let totalAmount = items.reduce((total, cur) => total + cur.Amount, 0);
      let newInvoice = { ...item };

      newInvoice.Amount = item.InvoiceBlanceAmount - totalAmount;
      this.accountRecharges.splice(index + 1, 0, newInvoice);
      console.log(this.accountRecharges);
    },
    // 差额
    // difference() {
    //   let total = this.accountRecharges.reduce(
    //     (total, cur) => total + cur.InvoiceBlanceAmount,
    //     0
    //   );
    //   return this.invoiceTotalAmount - total;
    // },
    onSubmit() {
      // if (!this.accountRecharges.every((v) => v.InvoiceType)) {
      //   this.$message.error("请选择发票类型");
      //   return;
      // }
      // if (!this.accountRecharges.every((v) => v.Invoicesubject)) {
      //   this.$message.error("请选择发票类目");
      //   return;
      // }
      // if (this.difference() != 0) {
      //   this.$message.error("有差额未选择开票");
      //   return;
      // }
      console.log(this.accountRecharges);
      this.$message.success("开票成功");
      this.$router.push({
        name: "发票信息",
        params: { accountRecharges: this.accountRecharges },
      });
    },
    // getUnitPrice(item) {
    //   item.unitPrice = item.Amount * (1 - 0.06);
    //   item.InvoiceTaxAmount = item.Amount;
    //   return item.unitPrice;
    // },
    // getAmount(item) {
    //   // item.Amount = this.$common.toFixed2(item.unitPrice);
    //   return item.Amount;
    // },
    // getTaxAmount(item) {
    //   item.TaxAmount = this.$common.toFixed2(item.Amount * 0.06);
    //   return item.TaxAmount;
    // },
    // getServiceName(item) {
    //   item.ServiceProviderName = item.ServiceName;
    //   item.ServiceProviderId = item.SID;
    // },
  },
};
</script>
<style lang="less" scoped>
.container {
  width: 100%;
  padding: 0 5rem;
  display: flex;
  flex-direction: column;
  .invoice-operation {
    padding: 2rem 0;
    //margin: 1rem;
    width: 100%;
  }
}

/* CSS Document */
.tabtop13 {
  margin-top: 13px;

  display: table;
  border-collapse: separate;

  text-indent: initial;
  // border-spacing: 2px;
  border-color: #c87c35 !important;
  border-top-color: #c87c35;
  border-right-color: #c87c35;
  border-bottom-color: #c87c35;
  border-left-color: #c87c35;

  td {
    background-color: #ffffff;
    height: 25px;
    line-height: 150%;
    text-align: center;
  }
}
.font-center {
  text-align: center;
}
.btbg {
  background: #e9faff !important;
}

.title {
  font-family: 微软雅黑;
  font-size: 26px;
  font-weight: bold;
  border-bottom: 1px dashed #c87c35;
  color: #255e95;
}
.titfont {
  font-family: 微软雅黑;
  font-size: 16px;
  font-weight: bold;
  color: #255e95;
  background-color: #e9faff;
}
</style>
